const express = require('express');
const mysql = require('mysql2/promise');
const bodyParser = require('body-parser');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const articlesRouter = require('./routes/articles');
const path = require('path');

const app = express();
const port = 3000;
const secretKey = 'your_secret_key';

// 数据库连接配置
const pool = mysql.createPool({
    host: 'localhost',
    user: 'your_username',
    password: 'your_password',
    database: 'bookstore',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));

// 错误处理中间件
const errorHandler = (err, req, res, next) => {
    console.error(err);
    res.status(500).json({ error: '服务器内部错误' });
};

// 验证 JWT 令牌中间件
const verifyToken = (req, res, next) => {
    const token = req.headers['authorization'];
    if (!token) {
        return res.status(403).json({ error: '未提供令牌' });
    }
    jwt.verify(token.replace('Bearer ', ''), secretKey, (err, decoded) => {
        if (err) {
            return res.status(401).json({ error: '无效的令牌' });
        }
        req.userId = decoded.userId;
        next();
    });
};

// 用户注册
app.post('/api/register', async (req, res) => {
    try {
        const { username, email, password } = req.body;
        const hashedPassword = await bcrypt.hash(password, 10);
        const [result] = await pool.execute(
            'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
            [username, email, hashedPassword]
        );
        res.status(201).json({ success: true, message: '注册成功' });
    } catch (error) {
        console.error('注册失败:', error);
        res.status(500).json({ success: false, message: '注册失败' });
    }
});

// 用户登录
app.post('/api/login', async (req, res) => {
    try {
        const { email, password } = req.body;
        const [rows] = await pool.execute('SELECT * FROM users WHERE email = ?', [email]);
        if (rows.length === 0) {
            return res.status(404).json({ success: false, message: '用户不存在' });
        }
        const user = rows[0];
        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) {
            return res.status(401).json({ success: false, message: '密码错误' });
        }
        const token = jwt.sign({ userId: user.id }, secretKey, { expiresIn: '1h' });
        res.json({ success: true, token });
    } catch (error) {
        console.error('登录失败:', error);
        res.status(500).json({ success: false, message: '登录失败' });
    }
});

// 获取所有图书
app.get('/api/books', async (req, res, next) => {
    try {
        const [rows] = await pool.execute('SELECT * FROM books');
        res.json(rows);
    } catch (error) {
        next(error);
    }
});

// 获取单本图书
app.get('/api/books/:id', async (req, res, next) => {
    try {
        const [rows] = await pool.execute('SELECT * FROM books WHERE id = ?', [req.params.id]);
        if (rows.length === 0) {
            return res.status(404).json({ error: '图书不存在' });
        }
        res.json(rows[0]);
    } catch (error) {
        next(error);
    }
});

// 添加到购物车
app.post('/api/cart', verifyToken, async (req, res, next) => {
    try {
        const { bookId, quantity } = req.body;
        const userId = req.userId;

        // 检查库存
        const [bookRows] = await pool.execute('SELECT inventory FROM books WHERE id = ?', [bookId]);
        if (bookRows.length === 0) {
            return res.status(404).json({ success: false, message: '图书不存在' });
        }

        if (bookRows[0].inventory < quantity) {
            return res.status(400).json({ success: false, message: '库存不足' });
        }

        // 检查购物车中是否已有该商品
        const [cartRows] = await pool.execute(
            'SELECT * FROM cart WHERE user_id = ? AND book_id = ?',
            [userId, bookId]
        );

        if (cartRows.length > 0) {
            // 更新数量
            await pool.execute(
                'UPDATE cart SET quantity = quantity + ? WHERE id = ?',
                [quantity, cartRows[0].id]
            );
        } else {
            // 添加新记录
            await pool.execute(
                'INSERT INTO cart (user_id, book_id, quantity) VALUES (?, ?, ?)',
                [userId, bookId, quantity]
            );
        }

        res.json({ success: true, message: '添加到购物车成功' });
    } catch (error) {
        next(error);
    }
});

// 从购物车中移除商品
app.delete('/api/cart/:id', verifyToken, async (req, res, next) => {
    try {
        const cartItemId = req.params.id;
        const userId = req.userId;
        const [result] = await pool.execute(
            'DELETE FROM cart WHERE id = ? AND user_id = ?',
            [cartItemId, userId]
        );
        if (result.affectedRows === 0) {
            return res.status(404).json({ success: false, message: '购物车商品不存在' });
        }
        res.json({ success: true, message: '从购物车中移除商品成功' });
    } catch (error) {
        next(error);
    }
});

// 结算购物车，创建订单
app.post('/api/orders', verifyToken, async (req, res, next) => {
    try {
        const userId = req.userId;
        const [cartRows] = await pool.execute('SELECT * FROM cart WHERE user_id = ?', [userId]);
        if (cartRows.length === 0) {
            return res.status(400).json({ success: false, message: '购物车为空' });
        }

        const orderDate = new Date().toISOString();
        const [orderResult] = await pool.execute(
            'INSERT INTO orders (user_id, order_date) VALUES (?, ?)',
            [userId, orderDate]
        );
        const orderId = orderResult.insertId;

        for (const cartItem of cartRows) {
            const { book_id, quantity } = cartItem;
            // 减少库存
            await pool.execute(
                'UPDATE books SET inventory = inventory - ? WHERE id = ?',
                [quantity, book_id]
            );
            // 添加订单明细
            await pool.execute(
                'INSERT INTO order_items (order_id, book_id, quantity) VALUES (?, ?, ?)',
                [orderId, book_id, quantity]
            );
        }

        // 清空购物车
        await pool.execute('DELETE FROM cart WHERE user_id = ?', [userId]);

        res.json({ success: true, message: '订单创建成功', orderId });
    } catch (error) {
        next(error);
    }
});

// 获取用户订单列表
app.get('/api/orders', verifyToken, async (req, res, next) => {
    try {
        const userId = req.userId;
        const [orders] = await pool.execute(
            'SELECT * FROM orders WHERE user_id = ?',
            [userId]
        );
        res.json(orders);
    } catch (error) {
        next(error);
    }
});

// 使用错误处理中间件
app.use(errorHandler);

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在端口 ${port}`);
});

app.use('/api/articles', articlesRouter);

const uploadRouter = require('./routes/upload');
app.use('/api/upload', uploadRouter);